package com.nowcoder.controller.advice;

import com.nowcoder.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author by lvshh
 * @version 1.0
 * @date 2020/4/30 14:16
 */
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
    @ExceptionHandler({Exception.class})
    public void handleRException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常：" + e.getMessage());
        for (StackTraceElement element :e.getStackTrace()){
            logger.error(element.toString());
        }

        //判断跳转的请求是普通请求还是异步请求
        String xRequestWith  = request.getHeader("x-requested-with");
        //如果是异步请求
        if ("XMLHttpRequest".equals(xRequestWith)){
            //响应内容的类型为文本字符串
            response.setContentType("application/plain;charset=utf-8");
            //响应输出流
            PrintWriter writer = response.getWriter();
            //输出JSON字符串
            writer.write(CommunityUtil.getJSONString(1,"服务器异常"));
        }else {
            //如果是普通请求就重定向到错误页面
            response.sendRedirect(request.getContextPath()+"/error");
        }
    }

}
